﻿using DyPrintForm.MainService;
using DyPrintForm.Method;
using Microsoft.Extensions.Caching.Memory;
using Microsoft.Web.WebView2.Core;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Speech.Synthesis;
using System.Threading.Tasks;
using System.Windows.Forms;
using log4net;
using log4net.Config;
using System.Diagnostics;

[assembly: XmlConfigurator(ConfigFile = "log4net.config", Watch = true)]

namespace DyPrintForm
{


    public partial class DyInit : Form
    {
        private static readonly ILog log = LogManager.GetLogger(typeof(DyInit));
        //礼物列表
        List<LW> _lwlist = new List<LW>();
        //头像获取JS
        string TouXiangJs = JsonHelper.GetJsonFile("./js/TouXiang.js");
        //是否语音播报
        public bool isYuyin = false;
        //礼物缓存
        public static IMemoryCache _cache = new MemoryCache(new MemoryCacheOptions());
        //默认礼物缓存时间15秒
        int lwCachetime = 15;
        //语音播报
        SpeechSynthesizer synthesizer = new SpeechSynthesizer();
        //打印机窗体
        Main main = new Main();
        //是否开启
        bool isPrint = false;
        public DyInit()
        {
            InitializeComponent();
            //获取礼物列表
            string absolutePath = System.IO.Path.GetFullPath("./Data/lw.json");
            string jsonlw = JsonHelper.GetJsonFile(absolutePath);
            if (!string.IsNullOrWhiteSpace(jsonlw))
            {
                _lwlist = JsonConvert.DeserializeObject<List<LW>>(jsonlw);
            }
            // 设置语音合成引擎的语音、语速、音量等参数
            synthesizer.SetOutputToDefaultAudioDevice();
            synthesizer.Volume = 100;
            synthesizer.Rate = 2;

        }

        private void btnStart_Click(object sender, EventArgs e)
        {
            //开启计时器，去除无人模式
            timer1.Start();
            timer2.Start();
            webView21.Invoke(new Action(async () =>
            {
                string Pinlun = JsonHelper.GetJsonFile("./js/PinLunLw.js");

                #region 获取直播间人数
                string zhnum = await webView21.CoreWebView2.ExecuteScriptAsync("document.getElementsByClassName('sz0V8anf')[0].textContent");
                zhnum = zhnum.Trim('"').Trim();
                if (zhnum.Contains('万'))
                {
                    lwCachetime = 60;
                }
                else
                {
                    if (zhnum!="null"&&Convert.ToInt32(zhnum) > 5000)
                    {
                        lwCachetime = 30;
                    }
                }
                #endregion

                await webView21.CoreWebView2.ExecuteScriptAsync(Pinlun);
            }));
        }

        private async void webView21_WebMessageReceived(object sender, Microsoft.Web.WebView2.Core.CoreWebView2WebMessageReceivedEventArgs e)
        {
            string imgJson = e.TryGetWebMessageAsString();
            string tag = "";
            if (imgJson.Length > 4)
            {
                tag = imgJson.Substring(0, 4);
                imgJson = imgJson.Replace(tag, "");
            }
            #region 消息区
            if (tag == "info")
            {
                string[] content = imgJson.Split('$');
                string lwz = "";
                int toGamenum = 0;
                string dataId = content[2].Trim('\'');
                if (content[0].Contains("送出了"))
                {
                    #region 记录参数
                    string username = ""; string num = "1"; string lw = ""; string lwurl = ""; string touXiang = "";
                    #endregion

                    //礼物列表不能为空
                    if (_lwlist != null)
                    {
                        //获取用户名
                        username = content[0].Replace("送出了", "$").Split('$')[0].Split('：')[0];
                        if (username.Contains("\n"))
                        {
                            //去除用户名粉丝灯牌名
                            username = username.Split('\n')[1];
                        }
                        //获取礼物个数
                        num = content[0].Substring(content[0].Length - 1, 1);
                        await webView21.CoreWebView2.ExecuteScriptAsync("document.getElementsByClassName('LU6dHmmD')[0].parentNode.parentNode.dataset.id;");
                        //获取礼物图片url
                        string[] lwsrc = OtherHelper.GetHtmlImageUrlList(content[1]);
                        string[] lwsrcsp = lwsrc[lwsrc.Length - 1].Split('/');
                        //匹配礼物名
                        #region 匹配礼物名
                        LW lwname = _lwlist.Where(n => n.src.Trim('\"').Contains(lwsrcsp[lwsrcsp.Length - 1])).FirstOrDefault();
                        lwurl = lwsrcsp[lwsrcsp.Length - 1];
                        if (lwname != null)
                        {
                            lwz = lwname.name;
                            lw = lwz.Trim('"');
                            content[0] = content[0] + "[" + lwz + "]";
                        }
                        else
                        {
                            //未知礼物进行记录
                            lw = "未知礼物";
                            LW lW = new LW
                            {
                                name = lw,
                                src = lwsrc[lwsrc.Length - 1],
                                price = "未知",
                            };
                            log.Info("未知礼物已添加到Data/lw.json请尽快修改名称" + JsonConvert.SerializeObject(lW));
                            content[0] = content[0] + "[" + lwsrc[lwsrc.Length - 1] + "]";
                            _lwlist.Add(lW);
                            string absolutePath = System.IO.Path.GetFullPath("./lw.json");
                            JsonHelper.WriteJsonFile(absolutePath, JsonConvert.SerializeObject(_lwlist));
                        }
                        #endregion

                    }

                    #region 缓存数据匹配输出文字到控制台(另加语音播报)
                    //获取缓存中是否用户送出礼物已存在
                    //评论区出现礼物证明礼物连送中止无需set缓存
                    object Hnum = _cache.Get(username.Trim() + "_" + lw.Trim());
                    string HString = "";
                    if (Hnum == null)
                    {
                        //等待半秒
                        await Task.Delay(500);
                        Hnum = _cache.Get(username.Trim() + "_" + lw.Trim());
                    }
                    //礼物再次为空，证明礼物没有出现在礼物区
                    if (Hnum == null)
                    {
                        if (lw.Trim().Contains("小心心") || lw.Trim().Contains("大啤酒"))
                        {
                            #region 匹配头像
                            //评论区的头像信息
                            string TxJs = TouXiangJs.Replace("@dataId", dataId);
                            string staus = await webView21.CoreWebView2.ExecuteScriptAsync(TxJs);
                            if (staus.Contains("suc"))
                            {
                                await Task.Delay(200);
                                string txurl = await webView21.CoreWebView2.ExecuteScriptAsync("document.getElementsByClassName('IrD6n6kd')[0].children[0].children[0].src;");
                                if (!string.IsNullOrWhiteSpace(txurl) && !txurl.Contains("null"))
                                {
                                    touXiang = txurl;
                                }
                            }

                            #endregion
                        }
                        toGamenum = Convert.ToInt32(num.Trim());
                        HString = username + "送出" + toGamenum.ToString() + lw;
                        if (isPrint)
                        {
                            GiftInit.MainInit(username, toGamenum, lw, touXiang, main);
                        }

                    }
                    else if (Hnum != null)
                    {
                        if (Convert.ToInt32(num.Trim()) > Convert.ToInt32(Hnum.ToString()))
                        {
                            if (lw.Trim().Contains("小心心") || lw.Trim().Contains("大啤酒"))
                            {
                                #region 匹配头像
                                //评论区的头像信息
                                string TxJs = TouXiangJs.Replace("@dataId", dataId);
                                string staus = await webView21.CoreWebView2.ExecuteScriptAsync(TxJs);
                                if (staus.Contains("suc"))
                                {
                                    await Task.Delay(200);
                                    string txurl = await webView21.CoreWebView2.ExecuteScriptAsync("document.getElementsByClassName('IrD6n6kd')[0].children[0].children[0].src;");
                                    if (!string.IsNullOrWhiteSpace(txurl) && !txurl.Contains("null"))
                                    {
                                        touXiang = txurl;
                                    }
                                }

                                #endregion
                            }
                            toGamenum = Convert.ToInt32(num.Trim()) - Convert.ToInt32(Hnum.ToString());
                            HString = username + "再送出" + toGamenum.ToString() + lw;
                            if (isPrint)
                            {
                                GiftInit.MainInit(username, toGamenum, lw, touXiang, main);
                            }

                        }
                    }
                    if (!string.IsNullOrWhiteSpace(HString))
                    {
                        txtControl.Invoke(new Action(() =>
                        {
                            if (txtControl.Text.Length > 2000)
                            {
                                txtControl.Clear();
                            }
                            txtControl.AppendText(HString + "\r\n");
                        }));
                        if (isYuyin)
                        {
                            synthesizer.SpeakAsync(HString);
                        }

                    }
                    #endregion

                }
                if (string.IsNullOrWhiteSpace(content[0]))
                {
                    return;
                }

                txtPl.Invoke(new Action(() =>
                {
                    if (txtPl.Text.Length > 2000)
                    {
                        txtPl.Clear();
                    }
                    txtPl.AppendText(content[0] + "\r\n");
                }));
            }
            #endregion
            #region 礼物区
            else if (tag == "liwu")
            {
                #region 礼物区参数
                string username = ""; string num = "1"; string lw = ""; string picHead = "";
                #endregion

                //分隔文本和Html内容
                string[] content = imgJson.Split('$');
                imgJson = content[0];
                string lwHtml = content[1];

                //分割礼物和用户名
                if (imgJson.Contains("送\n"))
                {
                    username = imgJson.Replace("送\n", "$").Split('$')[0].Split('\n')[0];
                    lw = imgJson.Replace("送\n", "$").Split('$')[1];
                }
                else if (imgJson.Contains("表示"))
                {
                    username = imgJson.Replace("表示", "$").Split('$')[0].Split('\n')[0];
                    lw = imgJson.Replace("表示", "$").Split('$')[1];
                }
                else
                {
                    username = "错误标记" + imgJson;
                    log.Error(username);
                }

                //分割礼物数量
                if (lw.Contains("x"))
                {
                    num = lw.Split('x')[1];
                    lw = lw.Split('x')[0];
                }
                #region 获取头像
                string[] lwsrc = OtherHelper.GetHtmlImageUrlList(lwHtml);
                if (lwsrc.Length > 0)
                {
                    picHead = lwsrc[0].Trim('"');
                }
                #endregion

                //打印礼物文本
                txtLw.Invoke(new Action(() =>
                {
                    if (txtLw.Text.Length > 2000)
                    {
                        txtLw.Clear();
                    }
                    txtLw.AppendText(imgJson + "\r\n");
                }));

                #region 礼物缓存
                int toGamenum = 0;
                object Hnum = _cache.Get(username.Trim() + "_" + lw.Trim());
                _cache.Set(username.Trim() + "_" + lw.Trim(), num.Trim(), new TimeSpan(0, 0, lwCachetime));
                string HString = "";
                if (Hnum != null)
                {
                    if (Convert.ToInt32(num.Trim()) > Convert.ToInt32(Hnum.ToString()))
                    {
                        toGamenum = Convert.ToInt32(num.Trim()) - Convert.ToInt32(Hnum.ToString());
                        HString = username + "再送出" + toGamenum.ToString() + lw;
                        if (isPrint)
                            GiftInit.MainInit(username, toGamenum, lw, picHead, main);
                    }
                    else
                    {
                        toGamenum = Convert.ToInt32(num.Trim());
                        HString = username + "送出" + toGamenum.ToString() + lw;
                        if (isPrint)
                            GiftInit.MainInit(username, toGamenum, lw, picHead, main);
                    }

                }
                else
                {
                    toGamenum = Convert.ToInt32(num.Trim());
                    HString = username + "送出" + toGamenum.ToString() + lw;
                    if (isPrint)
                        GiftInit.MainInit(username, toGamenum, lw, picHead, main);
                }
                if (!string.IsNullOrWhiteSpace(HString))
                {
                    txtControl.Invoke(new Action(() =>
                    {
                        if (txtControl.Text.Length > 2000)
                        {
                            txtControl.Clear();
                        }
                        txtControl.AppendText(HString + "\r\n");
                    }));
                    if (isYuyin)
                    {
                        synthesizer.SpeakAsync(HString);
                    }
                }
                #endregion

            }
            #endregion
        }

        private void btnInit_Click(object sender, EventArgs e)
        {
            if (webView21 != null && webView21.CoreWebView2 != null)
            {
                webView21.CoreWebView2.Navigate("https://live.douyin.com/" + txtRoomNum.Text);
            }
        }

        private void btnViedo_Click(object sender, EventArgs e)
        {
            if (btnViedo.Text.Contains("开启"))
            {
                isYuyin = true;
                btnViedo.Text = "关闭语音播报";
                synthesizer.Resume();
            }
            else
            {
                isYuyin = false;
                btnViedo.Text = "开启语音播报";
                synthesizer.Pause();
            }

        }

        private async void DyInit_Load(object sender, EventArgs e)
        {
            await webView21.EnsureCoreWebView2Async(null);
            webView21.CoreWebView2.NewWindowRequested += OnNewWindowRequested;
            webView21.CoreWebView2.WebMessageReceived += webView21_WebMessageReceived;
            //页面加载完成后
            webView21.CoreWebView2.DOMContentLoaded += CoreWebView2_DOMContentLoaded;
        }

        //DOM内容加载完成后
        private void CoreWebView2_DOMContentLoaded(object sender, CoreWebView2DOMContentLoadedEventArgs e)
        {
           


        }

        private void OnNewWindowRequested(object sender, CoreWebView2NewWindowRequestedEventArgs e)
        {
            var deferral = e.GetDeferral();
            e.NewWindow = webView21.CoreWebView2;
            deferral.Complete();
        }
        /// <summary>
        /// 礼物列表
        /// </summary>
        public class LW
        {
            public string src { get; set; }
            public string price { get; set; }
            public string name { get; set; }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            main.Show();
        }

        private void checkBox1_CheckedChanged(object sender, EventArgs e)
        {
            if (checkBox1.Checked)
            {
                isPrint = true;
                main.RetColor();
            }
            else
            {
                isPrint = false;
            }
        }

        private void btnClear_Click(object sender, EventArgs e)
        {
            main.ClearPrint();
        }
        //鼠标定时移动
        private async void timer1_Tick(object sender, EventArgs e)
        {
            this.WindowState = FormWindowState.Maximized;
            main.TopMost = false;
            this.TopMost = true;
            this.TopMost = false;
            Point point1 = new Point();
            Point point2 = new Point();
            point1.X = this.Location.X + this.splitContainer1.Panel1.Width;
            point1.Y = this.Location.Y + 100;
            point2.X = this.Location.X + this.splitContainer1.Panel1.Width + this.webView21.Width - 100;
            point2.Y = this.Location.Y + this.splitContainer1.Panel1.Height - 100;
            MockNet.MouseMoveToPoint(point1.X, point1.Y);
            await Task.Delay(1000);
            MockNet.MouseMoveToPoint(point2.X, point2.Y);
            main.TopMost = true;
        }
        public static long GetObjectSize(object obj)
        {
            // 强制进行一次垃圾回收，确保只统计目标对象的内存
            //GC.Collect();

            // 获取目标对象占用的内存大小
            long size = GC.GetTotalMemory(true);

            return size;
        }

        private void timer2_Tick(object sender, EventArgs e)
        {
            PerformanceCounter ramCounter = new PerformanceCounter("Memory", "Available MBytes");
            long thissize = GetObjectSize(this);

            var ramAvailable = ramCounter.NextValue();
            string ramAvaiableStr = string.Format("{0} MB", ramAvailable);

            this.label4.Invoke(new Action(() =>
            {
                label4.Text = "系统RAM:" + ramAvaiableStr + " 当前程序:" + thissize;
            }));
        }
    }
}
